package com.yboot.starter.tenant.core.mybatis;

import com.yboot.starter.common.core.security.SecurityUserVO;
import com.yboot.starter.common.core.security.UserContext;
import com.yboot.starter.mybatis.core.handle.InnerMetaObjectHandler;
import com.yboot.starter.tenant.config.TenantProperties;
import com.yboot.starter.tenant.core.context.TenantContextHolder;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

/**
 * public interface InnerMetaObjectHandler {
 * Object getFieldValue(String var1);
 * }
 * <p>
 * public void insertFill(MetaObject metaObject) {
 * if (!CollectionUtils.isEmpty(this.innerMetaObjectHandlers)) {
 * this.fillField(metaObject);
 * }
 * }
 */
public class BaseTenantEntityInnerMetaObjectHandler implements InitializingBean, InnerMetaObjectHandler {
    private final String tenantIdColumn;
    private final UserContext userContext;

    public BaseTenantEntityInnerMetaObjectHandler(TenantProperties tenantProperties, UserContext userContext) {
        this.tenantIdColumn = tenantProperties.getTenantIdColumn();
        this.userContext = userContext;
    }

    public void afterPropertiesSet() throws Exception {
        if (!StringUtils.hasLength(this.tenantIdColumn)) {
            throw new RuntimeException("列名 tenantIdColumn 不能为空");
        }
    }

    private String getTenantIdFromContext() {
        if (StringUtils.hasLength(TenantContextHolder.getTenantId())) {
            return TenantContextHolder.getTenantId();
        } else {
            SecurityUserVO user = userContext.getUser().orElseGet(SecurityUserVO::new);
            if (StringUtils.hasLength(user.getTenantId())) {
                return user.getTenantId();
            } else {
                throw new RuntimeException("未获取到租户信息");
            }
        }
    }

    public Object getFieldValue(String columnName) {
        return StringUtils.hasLength(columnName) && this.tenantIdColumn.equals(columnName) ? this.getTenantIdFromContext() : null;
    }

//    private AuthenticatedUser getAuthenticatedUser() {
//        return AuthenticationContextHolder.getAuthenticatedUser();
//    }
}
